﻿using UnityEngine;

/// <summary>
/// Tween the object's alpha. Works with both UI widgets as well as renderers.
/// </summary>

[AddComponentMenu("UGUI/Tween/Tween Alpha")]
public class UGUITweenAlpha : UGUITweener
{
    public override object fromValue { get { return from; } set { from = (float)value; } }
    public override object toValue { get { return to; } set { to = (float)value; } }

    [Range(0f, 1f)] public float from = 1f;
	[Range(0f, 1f)] public float to = 1f;

	bool mCached = false;
	CanvasGroup mRect;

    protected override void Start()
    {
        if (delay == 0)
        {
            value = from;
        }
        base.Start();
    }

	void Cache ()
	{
		mCached = true;
        mRect = gameObject.AddMissingComponent<CanvasGroup>();
	}

	/// <summary>
	/// Tween's current value.
	/// </summary>

	public float value
	{
		get
		{
			if (!mCached) Cache();
            return mRect.alpha;
		}
		set
		{
			if (!mCached) Cache();
            mRect.alpha = value;
		}
	}

	/// <summary>
	/// Tween the value.
	/// </summary>

	protected override void OnUpdate (float factor, bool isFinished) { value = Mathf.Lerp(from, to, factor); }

	/// <summary>
	/// Start the tweening operation.
	/// </summary>

	static public UGUITweenAlpha Begin (GameObject go, float duration, float alpha)
	{
        UGUITweenAlpha comp = UGUITweener.Begin<UGUITweenAlpha>(go, duration);
		comp.from = comp.value;
		comp.to = alpha;

		if (duration <= 0f)
		{
			comp.Sample(1f, true);
			comp.enabled = false;
		}
		return comp;
	}

	public override void SetStartToCurrentValue () { from = value; }
	public override void SetEndToCurrentValue () { to = value; }
}
